package com.xiezc.springboot_dht.model;

import com.xiezc.springboot_dht.util.Const;

import java.util.Arrays;
import java.util.Objects;

import static com.xiezc.springboot_dht.model.BeType.semicolon;

/**
 * @author wb-xzc291800
 */
public class BeString extends BeObject<byte[]> {

    public BeString(String val) {
        this(val.getBytes(Const.defaultCharset));
    }

    public BeString(byte[] val) {
        this.value = val;
    }

    @Override
    public byte[] getContent() {
        if (content != null) {
            return content;
        }
        byte[] head = Objects.toString(value.length).getBytes(Const.defaultCharset);
        content = new byte[head.length + 1 + value.length];
        System.arraycopy(head, 0, content, 0, head.length);
        content[head.length] = semicolon.getPre();
        System.arraycopy(value, 0, content, head.length + 1, value.length);
        return content;
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(this.value);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof BeString)) {
            return false;
        }
        BeString objBS = (BeString)obj;
        return Arrays.equals(objBS.getValue(), this.value);
    }

    @Override
    public String toString() {
        String s = new String(getValue(), Const.defaultCharset);
        return s;
    }
}
